package com.example.androidapp2;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import com.example.androidapp2.DbClasses.ItemCategoria;
import com.example.androidapp2.DbClasses.ItemIngresos;
import com.example.androidapp2.DbClasses.ItemTarjeta;
import com.example.androidapp2.DbClasses.Queries;
import com.example.androidapp2.DbClasses.TotalCategoria;
import com.example.androidapp2.DbClasses.Utils;
import com.xyzdesa.droidnomy.R;import android.content.ContentValues;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;

public class DbAdapter extends SQLiteOpenHelper {
	private static String DB_NAME = "DrNomy";	
	public static String DB_PATH = "/DroidNomy/";
	public static String AYUDAPATH = "Ayuda/";
	private static String IMAGES = "images/";
	public static String AYUDAP = "Ayuda.htm";
	private static String[] Archivos = new String[]{"MenuCate.png","MenuEntradas.png","PantallaPpalMenuDet.png","PopUpModifica.png","PopUpPorcentajes.png"};


	private SQLiteDatabase myDataBase; 
	private Context myContext;

	public DbAdapter(Context context,Resources r) throws IOException {		
		super(context, DB_NAME, null, 1);
		myContext = context;
		CopiarBaseInicial(r);
	}

	public void CopiarBaseInicial(Resources r) throws IOException
	{		
		AssetManager assetManager = r.getAssets();
		File sdCard, directory,file = null;

		if (Environment.getExternalStorageState().equals("mounted")) {
			sdCard = Environment.getExternalStorageDirectory();

			directory = new File(sdCard.getAbsolutePath() + DB_PATH);
			if(!directory.exists())
				directory.mkdirs();

			file = new File(sdCard.getAbsolutePath() + DB_PATH + DB_NAME);
			if(!file.exists()){
				File f = new File(Environment.getExternalStorageDirectory()+DB_PATH, DB_NAME);
				InputStream is = assetManager.open(DB_NAME);
				OutputStream os = new FileOutputStream(f, true);
				final int buffer_size = 1024 * 1024;
				byte[] bytes = new byte[buffer_size];
				for (;;)
				{
					int count = is.read(bytes, 0, buffer_size);
					if (count == -1)
						break;
					os.write(bytes, 0, count);
				}
				is.close();
				os.close();
			}
		}		
	}

	public void CopiarAyuda() throws IOException
	{
		AssetManager assetManager = myContext.getAssets();
		File sdCard, directory,file = null;

		if (Environment.getExternalStorageState().equals("mounted")) {
			sdCard = Environment.getExternalStorageDirectory();

			directory = new File(sdCard.getAbsolutePath() + DB_PATH);
			if(!directory.exists())
				directory.mkdirs();
			directory = new File(sdCard.getAbsolutePath() + DB_PATH + AYUDAPATH);
			if(!directory.exists())
				directory.mkdirs();
			directory = new File(sdCard.getAbsolutePath() + DB_PATH + AYUDAPATH + IMAGES);
			if(!directory.exists())
				directory.mkdirs();

			file = new File(sdCard.getAbsolutePath() + DB_PATH  + AYUDAPATH + AYUDAP);
			if(!file.exists()){
				File f = new File(Environment.getExternalStorageDirectory()+DB_PATH+AYUDAPATH,  AYUDAP);
				InputStream is = assetManager.open(AYUDAPATH + AYUDAP);
				OutputStream os = new FileOutputStream(f, true);
				final int buffer_size = 1024 * 1024;
				byte[] bytes = new byte[buffer_size];
				for (;;)
				{
					int count = is.read(bytes, 0, buffer_size);
					if (count == -1)
						break;
					os.write(bytes, 0, count);
				}
				is.close();
				os.close();
			}

			for (int i = 0; i < Archivos.length; i++) {
				file = new File(sdCard.getAbsolutePath() + DB_PATH + AYUDAPATH +IMAGES+Archivos[i]);
				if(!file.exists()){
					File f = new File(Environment.getExternalStorageDirectory()+DB_PATH+ AYUDAPATH +IMAGES, Archivos[i]);
					InputStream is = assetManager.open(AYUDAPATH +IMAGES+ Archivos[i]);
					OutputStream os = new FileOutputStream(f, true);
					final int buffer_size = 1024 * 1024;
					byte[] bytes = new byte[buffer_size];
					for (;;)
					{
						int count = is.read(bytes, 0, buffer_size);
						if (count == -1)
							break;
						os.write(bytes, 0, count);
					}
					is.close();
					os.close();
				}
			}

		}
	}

	public void createDataBase() throws IOException{

		boolean dbExist = checkDataBase();

		if(!dbExist){			
			this.getWritableDatabase();

			try {

				copyDataBase();

			} catch (IOException e) {

				throw new Error("Error copying database");

			}
		}

	}

	public boolean CheckearSD()
	{
		return (Environment.getExternalStorageState().equals("mounted"));
	}

	private boolean checkDataBase(){

		SQLiteDatabase checkDB = null;

		try{
			if (Environment.getExternalStorageState().equals("mounted")) {
				String sdCard = Environment.getExternalStorageDirectory().getPath();

				String myPath = sdCard + DB_PATH + DB_NAME;
				checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
			}
		}catch(SQLiteException e){
			throw e;
		}

		if(checkDB != null){
			checkDB.close();
		}

		return checkDB != null ? true : false;
	}

	private void copyDataBase() throws IOException{
		if (Environment.getExternalStorageState().equals("mounted")) {
			String sdCard = Environment.getExternalStorageDirectory().getPath();

			//Open your local db as the input stream
			InputStream myInput = myContext.getAssets().open(DB_NAME);

			// Path to the just created empty db
			String outFileName = sdCard + DB_PATH + DB_NAME;

			//Open the empty db as the output stream
			OutputStream myOutput = new FileOutputStream(outFileName);

			//transfer bytes from the inputfile to the outputfile
			byte[] buffer = new byte[1024];
			int length;
			while ((length = myInput.read(buffer))>0){
				myOutput.write(buffer, 0, length);
			}

			//Close the streams
			myOutput.flush();
			myOutput.close();
			myInput.close();
		}
	}

	public void openDataBase() throws SQLException{

		if (Environment.getExternalStorageState().equals("mounted")) {
			String sdCard = Environment.getExternalStorageDirectory().getPath();

			String myPath = sdCard + DB_PATH + DB_NAME;

			myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);			
		}
	}

	public void ActualizarBaseDatos()
	{		
		myDataBase.execSQL(Queries.CreateTablaTarjeta);
	}

	public void DeleteDataBase()
	{		
		File sdCard, directory,file = null;

		if (Environment.getExternalStorageState().equals("mounted")) {
			sdCard = Environment.getExternalStorageDirectory();

			directory = new File(sdCard.getAbsolutePath() + DB_PATH);
			if(directory.exists()){
				file = new File(sdCard.getAbsolutePath() + DB_PATH + DB_NAME);
				if(file.exists()){
					file.delete();
				}
			}
		}

	}

	@Override
	public synchronized void close() {

		if(myDataBase != null)
			myDataBase.close();

		super.close();

	}

	public int GetTotalMovimientos(String tipo)
	{				
		Cursor c = this.myDataBase.rawQuery(Queries.SelectTotalMovimientos, new String[]{tipo,Utils.medioEft,Utils.medioCred});
		c.moveToFirst();

		int x = c.getInt(c.getColumnIndex("Total"));
		c.close();

		return x;
	}

	public int GetTotalMovimientosMes(String tipo,String mes)
	{				
		Cursor c = this.myDataBase.rawQuery(Queries.SelectTotalMovimientosMes, new String[]{tipo,Utils.medioEft,Utils.medioCred,mes});
		c.moveToFirst();

		int x = c.getInt(c.getColumnIndex("Total"));
		c.close();

		return x;
	}

	public int GetTotalMovimientosAnio(String tipo,String anio)
	{				
		Cursor c = this.myDataBase.rawQuery(Queries.SelectTotalMovimientosMes, new String[]{tipo,Utils.medioEft,Utils.medioCred,anio});
		c.moveToFirst();

		int x = c.getInt(c.getColumnIndex("Total"));
		c.close();

		return x;
	}


	public List<String> GetFechasSpinner()
	{
		List<String> ls = new ArrayList<String>();
		Resources res = myContext.getResources();
		ls.add(res.getString(R.string.spnItemCate));

		Cursor c = this.myDataBase.rawQuery(Queries.SelectMovimientosFechas, new String[]{Utils.medioEft,Utils.medioCred});
		c.moveToFirst();
		if(c.getCount()>0){
			ls.add(c.getString(0).substring(4, 8));
			ls.add(c.getString(0).substring(2, 8).replace(c.getString(0).substring(2, 4), c.getString(0).substring(2, 4)+" - "));
			while(!c.isLast()) {
				c.moveToNext();
				if(!ls.contains(c.getString(0).substring(4, 8)))
					ls.add(c.getString(0).substring(4, 8));
				if(!ls.contains(c.getString(0).substring(2, 8).replace(c.getString(0).substring(2, 4), c.getString(0).substring(2, 4)+" - ")))
					ls.add(c.getString(0).substring(2, 8).replace(c.getString(0).substring(2, 4), c.getString(0).substring(2, 4)+" - "));
			}
		}
		c.close();	
		return ls;
	}

	public int GetIngresoAutomatico()
	{		
		InsertDataRefIfNotExist(Queries.SalarioAutomatico, "false");
		Cursor c = this.myDataBase.rawQuery(Queries.SelectSalarioAutomatico, null);
		c.moveToFirst();
		String str = c.getString(0);
		c.close();

		if(!str.equals("false"))
			return Integer.parseInt(str);		

		return 0;
	}

	public void SetTotalLaunches()
	{
		ContentValues values = new ContentValues();		
		values.put("Valor", GetTotalLaunches()+1);

		this.myDataBase.update("DataRef", values, Queries.WhereDataRef, new String[]{Queries.ContadorLaunches});		
	}

	public int GetTotalLaunches()
	{
		InsertDataRefIfNotExist(Queries.ContadorLaunches, "0");
		Cursor c = this.myDataBase.rawQuery(Queries.SelectTotalLaunches, null);
		c.moveToFirst();
		int x = c.getInt(0);
		c.close();

		return x;
	}

	public String GetFechaUltimoIngreso()
	{		
		InsertDataRefIfNotExist(Queries.UltimoIngreso, "");
		Cursor c = this.myDataBase.rawQuery(Queries.SelectUltimoIngreso, null);
		c.moveToFirst();
		String str = c.getString(0);
		c.close();

		return str;
	}
	
	public void SetAnsweredRating()
	{
		ContentValues values = new ContentValues();
		values.put("Valor", "true");
		
		this.myDataBase.update("DataRef", values, Queries.WhereDataRef, new String[]{Queries.EstadoRating});
	}
	
	public boolean GetAnsweredRating()
	{
		InsertDataRefIfNotExist(Queries.EstadoRating, "false");
		Cursor c = this.myDataBase.rawQuery(Queries.SelectEstadoRating, null);
		c.moveToFirst();
		String str = c.getString(0);
		c.close();

		return (str.equals("true"));
	}

	public void InsertDataRefIfNotExist(String controlNm, String value)
	{
		Cursor c = this.myDataBase.rawQuery(Queries.SelectDataRef.replace("?", controlNm), null);
		if(c.getCount()==0){
			ContentValues values = new ContentValues();
			values.put("Estado", 1);
			values.put("ControlNm", controlNm);
			values.put("Valor", value);

			this.myDataBase.insert("DataRef", null, values);
		}
		c.close();
	}

	public List<TotalCategoria> GetTotalesPorCategoria()
	{
		List<TotalCategoria> ls = new ArrayList<TotalCategoria>();
		List<ItemCategoria> lsCat = this.GetCategorias("spnCategorias",false,false);		
		String lang = (Locale.getDefault().getLanguage().equals(Utils.codEspanol))?Utils.codEspanol:Utils.codIngles;
		Cursor c = this.myDataBase.rawQuery(Queries.SelectTotalMovimientosPorCategoria,new String[]{Utils.medioEft,Utils.medioCred, lang});
		if(c.getCount()>0){
			c.moveToFirst();			
			ls.add(new TotalCategoria(c.getString(0),c.getInt(1)));
			while(!c.isLast()) {
				c.moveToNext();
				ls.add(new TotalCategoria(c.getString(0),c.getInt(1)));
			}
		}		
		c.close();

		if(ls.size()<lsCat.size())
			for (ItemCategoria it : lsCat) {
				boolean esta = false;
				for (TotalCategoria ct :ls ) {
					if(ct.Descripcion.equals(it.Descripcion))
						esta = true;
				}
				if(!esta)
					ls.add(new TotalCategoria(it.Descripcion, 0));
			}

		return ls;
	}

	public List<TotalCategoria> GetTotalesPorCategoriaAnio(String anio)
	{
		List<TotalCategoria> ls = new ArrayList<TotalCategoria>();
		List<ItemCategoria> lsCat = this.GetCategorias("spnCategorias",false,false);		
		String lang = (Locale.getDefault().getLanguage().equals(Utils.codEspanol))?Utils.codEspanol:Utils.codIngles;
		Cursor c = this.myDataBase.rawQuery(Queries.SelectTotalMovimientosPorCategoriaAnio,new String[]{Utils.medioEft,Utils.medioCred, lang,anio});
		if(c.getCount()>0){
			c.moveToFirst();			
			ls.add(new TotalCategoria(c.getString(0),c.getInt(1)));
			while(!c.isLast()) {
				c.moveToNext();
				ls.add(new TotalCategoria(c.getString(0),c.getInt(1)));
			}
		}		
		c.close();

		if(ls.size()<lsCat.size())
			for (ItemCategoria it : lsCat) {
				boolean esta = false;
				for (TotalCategoria ct :ls ) {
					if(ct.Descripcion.equals(it.Descripcion))
						esta = true;
				}
				if(!esta)
					ls.add(new TotalCategoria(it.Descripcion, 0));
			}

		return ls;
	}

	public List<TotalCategoria> GetTotalesPorCategoriaMes(String mes)
	{
		List<TotalCategoria> ls = new ArrayList<TotalCategoria>();
		List<ItemCategoria> lsCat = this.GetCategorias("spnCategorias",false,false);		
		String lang = (Locale.getDefault().getLanguage().equals(Utils.codEspanol))?Utils.codEspanol:Utils.codIngles;
		Cursor c = this.myDataBase.rawQuery(Queries.SelectTotalMovimientosPorCategoriaMes,new String[]{Utils.medioEft,Utils.medioCred, lang,mes});
		if(c.getCount()>0){
			c.moveToFirst();			
			ls.add(new TotalCategoria(c.getString(0),c.getInt(1)));
			while(!c.isLast()) {
				c.moveToNext();
				ls.add(new TotalCategoria(c.getString(0),c.getInt(1)));
			}
		}		
		c.close();

		if(ls.size()<lsCat.size())
			for (ItemCategoria it : lsCat) {
				boolean esta = false;
				for (TotalCategoria ct :ls ) {
					if(ct.Descripcion.equals(it.Descripcion))
						esta = true;
				}
				if(!esta)
					ls.add(new TotalCategoria(it.Descripcion, 0));
			}

		return ls;
	}

	public List<ItemIngresos> GetIngresos()
	{		
		List<ItemIngresos> ls = new ArrayList<ItemIngresos>();
		String lang = (Locale.getDefault().getLanguage().equals(Utils.codEspanol))?Utils.codEspanol:Utils.codIngles;
		Cursor c = this.myDataBase.rawQuery(Queries.SelectIngresos,new String[]{lang});
		if(c.getCount()>0){
			c.moveToFirst();
			ItemCategoria cat = (c.getString(0)!=null)?new ItemCategoria(c.getInt(8), c.getString(0), c.getInt(7)):null;
			ls.add(new ItemIngresos(c.getInt(2),c.getInt(1),cat,c.getString(3),c.getString(4),c.getInt(5),c.getInt(6)));
			while(!c.isLast()) {				
				c.moveToNext();	
				cat = (c.getString(0)!=null)?new ItemCategoria(c.getInt(8), c.getString(0), c.getInt(7)):null;;
				ls.add(new ItemIngresos(c.getInt(2),c.getInt(1),cat,c.getString(3),c.getString(4),c.getInt(5),c.getInt(6)));
			}
		}		
		c.close();

		return ls;
	}

	public List<ItemIngresos> GetIngresosMes(String mes)
	{
		List<ItemIngresos> ls = new ArrayList<ItemIngresos>();
		String lang = (Locale.getDefault().getLanguage().equals(Utils.codEspanol))?Utils.codEspanol:Utils.codIngles;
		Cursor c = this.myDataBase.rawQuery(Queries.SelectIngresosMes,new String[]{lang,mes,mes});
		if(c.getCount()>0){
			c.moveToFirst();
			ItemCategoria cat = (c.getString(0)!=null)?new ItemCategoria(c.getInt(8), c.getString(0), c.getInt(7)):null;
			ls.add(new ItemIngresos(c.getInt(2),c.getInt(1),cat,c.getString(3),c.getString(4),c.getInt(5),c.getInt(6)));
			while(!c.isLast()) {
				c.moveToNext();				
				cat = (c.getString(0)!=null)?new ItemCategoria(c.getInt(8), c.getString(0), c.getInt(7)):null;
				ls.add(new ItemIngresos(c.getInt(2),c.getInt(1),cat,c.getString(3),c.getString(4),c.getInt(5),c.getInt(6)));
			}
		}		
		c.close();

		return ls;
	}

	public List<ItemIngresos> GetIngresosAnio(String anio)
	{
		List<ItemIngresos> ls = new ArrayList<ItemIngresos>();
		String lang = (Locale.getDefault().getLanguage().equals(Utils.codEspanol))?Utils.codEspanol:Utils.codIngles;
		Cursor c = this.myDataBase.rawQuery(Queries.SelectIngresosAnio,new String[]{lang,anio,anio});
		if(c.getCount()>0){
			c.moveToFirst();
			ItemCategoria cat = (c.getString(0)!=null)?new ItemCategoria(c.getInt(8), c.getString(0), c.getInt(7)):null;
			ls.add(new ItemIngresos(c.getInt(2),c.getInt(1),cat,c.getString(3),c.getString(4),c.getInt(5),c.getInt(6)));
			while(!c.isLast()) {
				c.moveToNext();				
				cat = (c.getString(0)!=null)?new ItemCategoria(c.getInt(8), c.getString(0), c.getInt(7)):null;
				ls.add(new ItemIngresos(c.getInt(2),c.getInt(1),cat,c.getString(3),c.getString(4),c.getInt(5),c.getInt(6)));
			}
		}		
		c.close();

		return ls;
	}


	public ItemTarjeta GetTarjetaByIdMovimiento(int idMov)
	{
		Cursor c = myDataBase.rawQuery(Queries.SelectTarjetaPorIdMovimiento, new String[]{String.valueOf(idMov)});
		if(c.getCount()>0){
			c.moveToFirst();
			ItemTarjeta it = new ItemTarjeta(c.getInt(0), c.getInt(1), c.getInt(2), c.getInt(3),c.getString(4));
			c.close();
			return it;
		}else
			return null;
	}

	public int GetDiaCambioMes()
	{
		InsertDataRefIfNotExist(Queries.DiaCambioMes, "1");

		Cursor c = myDataBase.rawQuery(Queries.SelectCambioMes, null);
		c.moveToFirst();		
		int fc = Integer.parseInt(c.getString(0));
		c.close();

		return fc;
	}

	public void SetDiaCambioMes(int dia)
	{
		ContentValues values = new ContentValues();
		values.put("Valor", dia);
		
		this.myDataBase.update("DataRef", values, Queries.WhereDataRef, new String[]{Queries.DiaCambioMes});			
	}

	public int InsertMovimiento(int valor, String tipo, String fecha, String medio, int cate,int estado)
	{		
		ContentValues values = new ContentValues();
		values.put("Valor", valor);
		values.put("Tipo", tipo);
		values.put("Fecha", fecha);
		values.put("Medio", medio);
		values.put("Categoria", cate);
		values.put("Estado", estado);

		this.myDataBase.insert("Movimientos", null, values);

		return SelectIdUltimoMovimiento(true);
	}	

	public int SelectIdUltimoMovimiento(boolean estado)
	{
		String sql = Queries.SelectIdUltimoMovimiento + ((estado)?Queries.WhereEstado.replace("?", "1"):"");

		Cursor c  = myDataBase.rawQuery(sql, null);
		if(c.getCount()>0){	
			c.moveToFirst();
			int x = c.getInt(0);
			c.close();
			return x;
		}
		else
			return 0;
	}

	public void UpdateMovimientos(int id, int valor, int codCategoria, String medio,String fecha)
	{
		ContentValues values = new ContentValues();
		values.put("Valor", valor);
		values.put("Medio", medio);
		values.put("Categoria", codCategoria);
		values.put("Fecha", fecha);

		this.myDataBase.update("Movimientos", values,"IdMovimiento = ?",new String[]{String.valueOf(id)});
	}

	public void InsertTarjeta(int idMov, int cuotas, int pagos,int idPago)
	{		
		ContentValues values = new ContentValues();
		values.put("IdMovimiento", idMov);
		values.put("Cuotas", cuotas);
		values.put("Pagos", pagos);
		values.put("Fecha", Utils.GetFecha());
		values.put("IdMovPago", idPago);

		this.myDataBase.insert("Tarjeta", null, values);
	}

	public void DeleteTarjetasPorIdMovimiento(int idMov)
	{
		this.myDataBase.delete("Tarjeta", "IdMovimiento =  ?", new String[]{String.valueOf(idMov)});
	}

	public void DeleteMovimientosPagos(int idMov)
	{
		int[] ls = new int[0];

		Cursor c = this.myDataBase.rawQuery(Queries.SelectIdsPagosTarjeta, new String[]{String.valueOf(idMov)});
		if(c.getCount()>0){
			ls = new int[c.getCount()];
			int i=0;
			c.moveToFirst();
			ls[i]=c.getInt(0);
			while(!c.isLast())
			{				
				c.moveToNext();
				i++;
				ls[i]=c.getInt(0);
			}
		}
		c.close();

		InactivarPorVariosIds(ls);
	}

	public void UpdateMovimientosAInactivo(String condicion)
	{
		ContentValues values = new ContentValues();
		values.put("Estado", 0);		

		this.myDataBase.update("Movimientos", values,"IdMovimiento in "+ condicion,null);		
	}

	public void InactivarTodos()
	{
		ContentValues values = new ContentValues();
		values.put("Estado", 0);		

		this.myDataBase.update("Movimientos", values,null,null);		
	}


	public void InactivarUltimo()
	{
		UpdateMovimientosAInactivo("(" + Queries.SelectIdUltimoMovimiento + ")");
	}

	public void InactivarPorId(int id)
	{
		UpdateMovimientosAInactivo("("+id+")");
	}

	public void InactivarPorVariosIds(int[] ids)
	{
		String ls = "(";

		for (int i = 0; i < ids.length; i++) {
			ls+=String.valueOf(ids[i]);
			if(i != ids.length-1)
				ls+=",";
		}		
		ls+=")";

		UpdateMovimientosAInactivo(ls);
	}

	public void PagarMovimientosTarjeta(List<ItemIngresos> ls)
	{		
		for (ItemIngresos str : ls){						
			InsertMovimiento(str.Valor/str.Cuotas, Utils.codEgreso, Utils.GetFecha(), Utils.medioCred, str.Categoria.Codigo, 3);			
			InsertTarjeta(str.Id,str.Cuotas,str.Pagos+1,SelectIdUltimoMovimiento(false));
		}
	}

	public void InactivarMes(String fecha)
	{
		String mes = fecha.substring(2, 8);
		UpdateMovimientosAInactivo("(" + Queries.SelectIdsMovimientosMes.replace("?", mes) + ")");
	}

	public void InactivarAnual(String fecha)
	{
		String anio = fecha.substring(4, 8);
		UpdateMovimientosAInactivo("(" + Queries.SelectIdsMovimientosAnio.replace("?", anio) + ")");
	}

	public void SetSueldoAutomatico(String val)
	{
		ContentValues values = new ContentValues();
		values.put("Valor", val);		

		this.myDataBase.update("DataRef", values,"ControlNm = 'SalarioAutomatico'",null);
	}

	public void ClearSueldoAutomatico()
	{
		ContentValues values = new ContentValues();
		values.put("Valor", "false");		

		this.myDataBase.update("DataRef", values,"ControlNm = 'SalarioAutomatico'",null);		
	}

	public boolean SetUltimoIngreso()
	{
		int Sueldo = GetIngresoAutomatico();
		if(this.GetTotalMovimientosMes("In",Utils.GetMesAnio())==0 && Sueldo == 0)
			return true;

		boolean abrePopUp = false;		
		String fecha = GetFechaUltimoIngreso();

		if(fecha.length() > 0){
			int dia = Integer.parseInt(fecha.substring(0,2));
			int hoy = Utils.GetDia();

			if(dia != hoy && hoy == this.GetDiaCambioMes())				
				if(Sueldo>0)
					this.InsertMovimiento(Sueldo, "In", Utils.GetFecha(), "EFT", 0,1);
				else 
					abrePopUp= true;
		}

		ContentValues values = new ContentValues();
		values.put("Valor", Utils.GetFecha());		

		this.myDataBase.update("DataRef", values,"ControlNm = 'UltimoIngreso'",null);		

		return abrePopUp;
	}

	public void InsertarCategoria(String nombre)
	{				
		Cursor c = myDataBase.rawQuery(Queries.SelectMaxIdCategorias, null); 
		c.moveToFirst();
		int cod = c.getInt(0)+1;
		c.close();

		ContentValues values = new ContentValues();		
		values.put("Codigo", cod);
		values.put("ControlNm", "spnCategorias");
		values.put("Valor", nombre);
		values.put("Estado",1);

		this.myDataBase.insert("DataRef", null, values);
	}

	public void ActivarCategoria(int cod)
	{
		ContentValues values = new ContentValues();
		values.put("Estado", 1);		

		this.myDataBase.update("DataRef", values,"ControlNm = 'spnCategorias' AND Codigo = ?",new String[]{String.valueOf(cod)});
	}


	public void InactivarCategoria(int cod)
	{
		ContentValues values = new ContentValues();
		values.put("Estado", 0);		

		this.myDataBase.update("DataRef", values,"ControlNm = 'spnCategorias' AND Codigo = ?",new String[]{String.valueOf(cod)});
	}

	public List<ItemCategoria> GetCategorias(String nombre, Boolean estado,Boolean addedCats)
	{			
		String lang = (Locale.getDefault().getLanguage().equals(Utils.codEspanol))?Utils.codEspanol:Utils.codIngles;
		String where = " ControlNm ='"+nombre+"' ";
		if(addedCats)
			where+=Queries.WhereIdiomaNull;
		else 
			where+=Queries.WhereIdioma.replace("?", "'"+lang+"'");

		if(estado)
			where += Queries.WhereEstado.replace("?", "1");

		List<ItemCategoria> ls = new ArrayList<ItemCategoria>();
		Cursor c = this.myDataBase.rawQuery(Queries.SelectCategorias + where + Queries.Order.replace("?", "Codigo"),null);
		if(c.getCount()>0){
			c.moveToFirst();
			ls.add(new ItemCategoria(c.getInt(0), c.getString(1),c.getInt(2)));
			while(!c.isLast()) {
				c.moveToNext();
				ls.add(new ItemCategoria(c.getInt(0), c.getString(1),c.getInt(2)));
			}
		}
		c.close();

		return ls;
	}

	@Override
	public void onCreate(SQLiteDatabase arg0) {}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {}

}
